package top.drinyeit.weilong.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import top.drinyeit.weilong.R;
import top.drinyeit.weilong.app.Constant;
import top.drinyeit.weilong.base.BaseActivity;
import top.drinyeit.weilong.dialog.BottomDialog;
import top.drinyeit.weilong.presenter.EditCompanyPresenter;
import top.drinyeit.weilong.retrofit.HttpResponse;
import top.drinyeit.weilong.retrofit.RetrofitMethod;
import top.drinyeit.weilong.retrofit.subscriber.CommonSubscriber;
import top.drinyeit.weilong.retrofit.subscriber.SubscriberListener;
import top.drinyeit.weilong.util.SPUtil;

import static top.drinyeit.weilong.app.Constant.ACCESS_KEY_ID;
import static top.drinyeit.weilong.app.Constant.ACCESS_KEY_SECRET;
import static top.drinyeit.weilong.app.Constant.BUCKET_HEAD;
import static top.drinyeit.weilong.app.Constant.COMMON_SUCCESS;
import static top.drinyeit.weilong.app.Constant.DEFAULT_TIMEOUT;
import static top.drinyeit.weilong.app.Constant.END_POINT;

/**
 * Created by wu on 2018/1/23.
 */

public class UploadLicenseActivity extends BaseActivity {
    public RelativeLayout license;
    public TextView licenseText;
    public ImageView licenseImg;
    BottomDialog bottomDialog;
    Bitmap headBitmap;
    private OSS oss;
    private static final int REQUEST_PICK = 1;
    private static final int REQUEST_CAPTURE = 2;
    private static final int REQ_CODE_PERMISSION = 0x1111;
    StringBuilder objectKey;
    private EditCompanyPresenter editCompanyPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_license);

        initView();
        initData();
        initListener();
        setTitle(true, "上传营业执照");
    }

    private void initView() {
        license = findViewById(R.id.rl_license);
        licenseText = findViewById(R.id.tv_license);
        licenseImg = findViewById(R.id.iv_license);
    }

    private void initData() {
        editCompanyPresenter = new EditCompanyPresenter(this);
        editCompanyPresenter.getCompany();
    }

    private void initListener() {
        license.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog = new BottomDialog(UploadLicenseActivity.this, R.layout.dialog_bottom);
                bottomDialog.show();
                LinearLayout ch0 = bottomDialog.findViewById(R.id.ch0);
                LinearLayout ch1 = bottomDialog.findViewById(R.id.ch1);
                TextView choose0 = bottomDialog.findViewById(R.id.choose0);
                TextView choose1 = bottomDialog.findViewById(R.id.choose1);
                TextView dialog_cancel = bottomDialog.findViewById(R.id.dialog_cancel);
                ImageView take_pictures = bottomDialog.findViewById(R.id.take_pictures);
                ImageView photographs = bottomDialog.findViewById(R.id.photographs);

                take_pictures.setVisibility(View.VISIBLE);
                photographs.setVisibility(View.VISIBLE);

                dialog_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });

                choose0.setText("拍照");
                choose1.setText("照片");
                //拍照
                ch0.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (ContextCompat.checkSelfPermission(UploadLicenseActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                            // Do not have the permission of camera, request it.
                            ActivityCompat.requestPermissions(UploadLicenseActivity.this, new String[]{Manifest.permission.CAMERA}, REQ_CODE_PERMISSION);
                        } else {
                            // Have gotten the permission
                            getImageFromCamera();
                        }
                    }
                });
                //选择照片
                ch1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, REQUEST_PICK);
                    }
                });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                bottomDialog.dismiss();
                if (resultCode == RESULT_OK) {
                    Uri uri;
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
                    if (data.getData() != null) {
                        uri = data.getData();
                    } else {
                        uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
                    }
                    String cropImagePath = getRealFilePathFromUri(getApplicationContext(), uri);
                    headBitmap = BitmapFactory.decodeFile(cropImagePath);
                    //上传至阿里云
                    initOss();
                    uploadHeadView(80);
                }
                break;
            case REQUEST_PICK:  //调用系统相册返回
                bottomDialog.dismiss();
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    if (uri == null) {
                        return;
                    }
                    String cropImagePath = getRealFilePathFromUri(getApplicationContext(), uri);
                    headBitmap = BitmapFactory.decodeFile(cropImagePath);
                    //上传至阿里云
                    initOss();
                    uploadHeadView(80);
                }
                break;
        }
    }

    protected void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
            startActivityForResult(getImageByCamera, REQUEST_CAPTURE);
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    public static String getRealFilePathFromUri(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equalsIgnoreCase(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equalsIgnoreCase(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    private void initOss() {
//        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider("", "", "");
        OSSCredentialProvider credential = new OSSPlainTextAKSKCredentialProvider(ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(DEFAULT_TIMEOUT * 1000);
        conf.setSocketTimeout(DEFAULT_TIMEOUT * 1000);
        conf.setMaxConcurrentRequest(2); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSSLog.enableLog();
        oss = new OSSClient(getApplicationContext(), END_POINT, credential, conf);
    }

    private void uploadHeadView(int quality) {
        byte[] headData = null;
        if (headBitmap == null) {
            return;
        } else {
            ByteArrayOutputStream headStream = new ByteArrayOutputStream();
            headBitmap.compress(Bitmap.CompressFormat.JPEG, quality, headStream);
            headData = headStream.toByteArray();
        }
        //构造上传请求
        PutObjectRequest put = new PutObjectRequest(BUCKET_HEAD, initObjectKey(), headData);
        // 异步上传时可以设置进度回调
//        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
//            @Override
//            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
//                Log.e("----11-----", "");
//                Log.e("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
//            }
//        });
        final Map<String, Object> map = new HashMap<>();
        final String user_id = SPUtil.getShareString(Constant.USER_ID);
        map.put("action", "company_authentication");
        map.put("user_id", user_id);
        map.put("license_picture", objectKey.toString());
        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.e("===PutObject===", "UploadSuccess");
                Log.e("===ETag===", result.getETag());
                Log.e("===RequestId===", result.getRequestId());
                CommonSubscriber<HttpResponse<String>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<String>>() {
                    @Override
                    public void onError(String e, int code) {
                        showToastMsg("错误，请重新操作！");
                    }

                    @Override
                    public void onNext(top.drinyeit.weilong.retrofit.HttpResponse<String> o) {
                        showToastMsg(o.getMessage());
                        if (o.getCode() == COMMON_SUCCESS) {
                            initData();
                        }
                    }
                });
                RetrofitMethod.getInstance().editCompany(subscriber, map);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
    }

    private String initObjectKey() {
        objectKey = new StringBuilder()
                .append("license_view/")
//                .append(DateUtil.getYMDString())
                .append(SPUtil.getShareString(Constant.BUCKET_HEAD))
                .append("/")
                .append(System.currentTimeMillis())
//                .append(new Random().nextInt(9))
//                .append(new Random().nextInt(9))
//                .append(new Random().nextInt(9))
                .append("_")
                .append(SPUtil.getShareString(Constant.LOGIN_PHONE))
                .append(".jpg");
        Log.i("===ObjectKey===", objectKey.toString());
        return objectKey.toString();
    }
}
